package top.kaoshanji.q1ch07a.web;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import top.kaoshanji.q1ch07a.model.Spitter;
import top.kaoshanji.q1ch07a.vo.SpitterForm;

/**
 * @author kaoshanji
 * ^_^
 * create time 2025/4/25 11:35
 */
@Controller
@RequestMapping("/spitter")
public class SpitterController {

    @RequestMapping(value="/register", method= RequestMethod.GET)
    public String showRegistrationForm(Model model) {
        model.addAttribute("spitter" ,new Spitter());
        return "registerFormPage";
    }

    /**
     * 代码清单-q1ch07a-02：以MultipartFile的形式接受上传的文件
     * @param profilePicture MultipartFile
     * @param spitterForm SpitterForm
     * @return redirect
     */
    @RequestMapping(value="/register", method= RequestMethod.POST)
    public String processRegistration(@RequestPart("profilePicture") MultipartFile profilePicture, SpitterForm spitterForm) {

        Spitter spitter = spitterForm.toSpitter();

        System.out.println("文件原始名称：" + profilePicture.getOriginalFilename());
        System.out.println("文件大小：" + profilePicture.getSize());

        String userName = spitter.getUsername();
        if (userName == null || userName.isEmpty()) {
            userName = "userName";
        }

        return "redirect:/spitter/spitterDetail/" + userName;
    }

    @RequestMapping(value="/spitterDetail/{username}", method=RequestMethod.GET)
    public String showSpitterProfile(
            @PathVariable String username, Model model) {

        Spitter spitter = new Spitter();
        spitter.setUsername(username);

        model.addAttribute("spitter", spitter);

        return "profilePage";
    }




}
